package com.czp.opensource.profiler.log;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import com.czp.opensource.profiler.cfg.Configuration;

/**
 * 
 * @description
 *       <p>异步的方式记录日志</p>
 * @author 
 *        Czp
 * @version 
 *        1.0(2014-5-10)
 *
 */
public class LogingThread extends Thread{

	/**
	 * Singleton
	 */
	private static volatile LogingThread logingThread;
	/**
	 * 日志阻塞队列
	 */
	private volatile BlockingQueue<Object> logQueue;
	
	/**
	 * 线程退出标志
	 */
	private volatile boolean isStop;
	
	private boolean isLogDebug;
	
	/**
	 * Singleton is Daemon thread
	 */
	private LogingThread() {
		logQueue = new LinkedBlockingQueue<Object>();
		isLogDebug = Configuration.isDebug(Configuration.IS_DEBUG_ENABLE);
		setDaemon(true);
	}
	/**
	 * 
	 * @desc:
	 *     <p>添加异步消息:ThreadName-ThreadId-Message</p> 
	 * @param message
	 */
    private void add(Object message)
    {
    	if(message!=null)
    	{
    		Thread currentThread = Thread.currentThread();
			StringBuilder msg =  new StringBuilder(currentThread.getName());
			msg.append("-").append(currentThread.getId());
			msg.append("-").append(message);
    		logQueue.add(msg);
    	}	
    }
	/**
	 * 
	 * @desc:
	 *     <p>获取实例的唯一入口</p> 
	 * @return
	 */
	public static LogingThread getInstance(){
		if(logingThread==null)
		{
			synchronized (LogingThread.class) {
				if(logingThread==null)
				{
					logingThread = new LogingThread();
				}
			}
		}
		return logingThread;
	}
	/**
	 * 
	 * @desc:
	 *     <p>异步记录日志:debug级别</p> 
	 * @param message
	 */
	public void debug(Object message)
	{
		if(isLogDebug)
			add(message);
	}
	/**
	 * 
	 * @desc:
	 *     <p>异步记录日志:info级别</p> 
	 * @param message
	 */
	public void info(Object message){
		add(message);
	}
	/**
	 * 
	 * @desc:
	 *     <p>终止日志线程,添加一个消息避免阻塞</p>
	 */
	public void shutDown(){
		logQueue.add("shutDown");
		isStop = true;
		logQueue = null;
		logingThread = null;
	}
	@Override
	public void run() {
		while(!isStop)
		{
			try {
				Object log = logQueue.take();
				System.out.println(log);
			} catch (Exception e) {
				Thread.interrupted();
			}
		}	
	}
	
	
}
